package org.uned.agonzalo16.bitacora.web.user;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.uned.agonzalo16.bitacora.dao.UserDao;
import org.uned.agonzalo16.bitacora.domain.User;
import org.uned.agonzalo16.bitacora.service.security.AuthenticatedUser;

@RequestMapping("/currentuser")
@Controller
@SessionAttributes({ "userAttribute" })
public class CurrentuserController {

	@Autowired
	private UserDao userDao;

	@Autowired
	private ChangePasswordValidator changePasswordValidator;

	@Autowired
	private UserValidator userValidator;

	@RequestMapping(method = RequestMethod.GET, value = "/show")
	public String show(@ModelAttribute("userAttribute") AuthenticatedUser user, Model model) {
		model.addAttribute("user", new UserForm(userDao.get(user.getId())));
		return "currentuser/update";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/update")
	public String update(@Valid @ModelAttribute("user") UserForm form, BindingResult result, @ModelAttribute("userAttribute") AuthenticatedUser authUser) {

		form.setId(authUser.getId());
		userValidator.validate(form, result);

		if (result.hasErrors()) {
			return "currentuser/update";
		}

		User user = userDao.get(authUser.getId());
		user.setEmail(form.getEmail());
		user.setLocalization(form.getLocalization());
		user.setUsername(form.getUsername());
		user.setWebSite(form.getWebSite());

		userDao.merge(user);

		return "redirect:/currentuser/show";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/pass")
	public String pass(@ModelAttribute("userAttribute") AuthenticatedUser user, Model model) {
		model.addAttribute("passForm", new ChangePasswordForm(userDao.get(user.getId())));
		return "currentuser/pass";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/changePass")
	public String changePass(@Valid @ModelAttribute("passForm") ChangePasswordForm form, BindingResult result, @ModelAttribute("userAttribute") AuthenticatedUser authUser) {

		form.setId(authUser.getId());
		changePasswordValidator.validate(form, result);

		if (result.hasErrors()) {
			return "currentuser/pass";
		}

		User user = userDao.get(authUser.getId());
		user.setPassword(form.getNewPassword());

		userDao.merge(user);

		return "redirect:/currentuser/show";
	}

}
